package com.jzy.util;

import com.jzy.dto.Types;
import com.jzy.entity.Vo.ContentVo;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;

public class PredicateUtil {

    public static Predicate getPredicateByType(String type, Root<?> root, CriteriaBuilder criteriaBuilder) {
        ArrayList<Predicate> predicates = new ArrayList<>();
        predicates.add(criteriaBuilder.equal(root.get("type"), type));
        int size = predicates.size();
        return criteriaBuilder.and(predicates.toArray(new Predicate[size]));
    }

    public static Specification<ContentVo> getContentVoSpecification() {
        return (Specification<ContentVo>) (root, query, criteriaBuilder) -> {
            ArrayList<Predicate> predicates = new ArrayList<>();
            predicates.add(criteriaBuilder.equal(root.get("status"), Types.PUBLISH.getType()));
            predicates.add(criteriaBuilder.equal(root.get("type"), Types.ARTICLE.getType()));
            int size = predicates.size();
            return criteriaBuilder.and(predicates.toArray(new Predicate[size]));
        };
    }

    public static Sort getOrders() {
        ArrayList<Sort.Order> orders = new ArrayList<>();
        orders.add(new Sort.Order(Sort.Direction.DESC, "created"));
        return Sort.by(orders);
    }
}
